package com.syyo.gulimall.cart.interceptor;

import com.syyo.common.constant.AuthConstant;
import com.syyo.common.constant.CartConstant;
import com.syyo.common.vo.MemberVo;
import com.syyo.gulimall.cart.vo.UserInfoTo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * @ author: wang
 * @ date: 2021/4/20 16:14
 * @ Description: 购物车拦截器
 * <p>
 * 在执行目标状态之前，判断用户状态，并封装传递给controller
 */
public class CartInterceptor implements HandlerInterceptor {


    public static ThreadLocal<UserInfoTo> threadLocal = new ThreadLocal<>();


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        UserInfoTo userInfoTo = new UserInfoTo();

        HttpSession session = request.getSession();

        MemberVo attribute = (MemberVo) session.getAttribute(AuthConstant.LOGIN_USER);

        if (attribute != null) {
            // 已登录，获取用户购物车
            userInfoTo.setUserId(Long.parseLong(attribute.getId().toString()));
        }
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                if (CartConstant.TEMP_USER_COOKIE_NAME.equals(cookie.getName())) {
                    userInfoTo.setUserKey(cookie.getValue());
                    userInfoTo.setIsTempUser(true);
                }

            }
        }

        if (StringUtils.isEmpty(userInfoTo.getUserKey())) {
            // 没有临时用户key，自动分配一个
            String uuid = UUID.randomUUID().toString();
            userInfoTo.setUserKey(uuid);
        }

        // 目标方法指向性之前，把信息保存在线程里
        threadLocal.set(userInfoTo);
        return true;
    }

    /**
     * 分配临时用户
     *
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

        UserInfoTo userInfoTo = threadLocal.get();
        if (!userInfoTo.getIsTempUser()) {
            Cookie cookie = new Cookie(CartConstant.TEMP_USER_COOKIE_NAME, userInfoTo.getUserKey());
            cookie.setDomain("gulimall.com");
            cookie.setMaxAge(CartConstant.TEMP_USER_COOKIE_TIMEOUT);
            response.addCookie(cookie);
        }
    }
}
